"""
@File    : conftest.py
@Time    : 2019/7/18 16:00
@Author  : LiuFeiYu
@Email   : liufeiyu@sunrise.net
@Software: PyCharm
"""
import os
import sys
import pytest
import pymysql
import jira
import Common.Consts
import json
from Common.ConnectJenkins import ConnectJenkins
from Common.Request import Request
from Common.GetKey import GetKey
from Settings.Config import Config
from os import path
from selenium import webdriver
from _pytest.runner import pytest_runtest_makereport

"""
@allure.feature # 用于定义被测试的功能，被测产品的需求点
@allure.story # 用于定义被测功能的用户场景，即子功能点
@allure.severity #用于定义用例优先级
@allure.issue #用于定义问题表识，关联标识已有的问题，可为一个url链接地址
@allure.testcase #用于用例标识，关联标识用例，可为一个url链接地址
@allure.attach # 用于向测试报告中输入一些附加的信息，通常是一些测试数据信息
@allure.step # 用于将一些通用的函数作为测试步骤输出到报告，调用此函数的地方会向报告中输出步骤
@allure.environment(environment=env) #用于定义environment(环境变量) allure-pytest无此方法，用description(详细描述)代替
@pytest.fixture()
-----------------------------------------------------------------------------
# 自定义用例的执行顺序：fixture
# conftest.py配置数据共享，不需要导入新包就能自动找到一些配置
# scope="module"（可以实现多个.py跨文件共享前置）
# scope="session"（以实现多个.py跨文件使用一个session来完成多个用例）
# scope="function"(默认值)
# scope="class"
"""
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))


@pytest.fixture(scope='module')
def setup():
    """所有用例执行之前执行一次"""
    # 登录接口地址和请求数据
    login_url = Config().loginHost_debug
    login_data = Config().loginInfo_debug
    # 发起请求
    result = Request.post_request(url=login_url, json=json.loads(login_data))
    # 获取返回值的最新token
    new_token = str(GetKey.get_key(result, 'token'))
    # 写入配置文件
    Config().set_conf(Config.TITLE_DEBUG, Config.VALUE_TOKEN, new_token)


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    """
    获取用例执行后是否失败,并设置item属性rep_call,
    方便提供给error_handling方法使用
    """
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)
    # if rep.when == 'call':
    #     if rep.failed:
    #         print(f"{item.name}错误啦")


@pytest.fixture
def error_handling(request):
    """
    检查用例是否失败,失败后做的清理工作
    """
    yield
    if request.node.rep_setup.failed:
        # print("setup失败啦", request.node.nodeid)
        raise Exception(f'setup失败啦", {request.node.nodeid}')
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            # 失败后,全部变量增加1
            Common.Consts.API_RESPONSE_NUMBER += 1
        else:
            Common.Consts.API_TRUE_RESPONSE_NUMBER += 1
            # print(f"用例失败啦", request.node.nodeid)


@pytest.fixture(scope="module")
def db_181_hydd():
    """
    db_host: 192.168.10.181
    """
    db_obj = pymysql.connect(host=Config().connect_url_db_181,
                             port=3306,
                             user=Config().username_db_181,
                             password=Config().password_db_181,
                             database=Config().hy_hydd_default_database_181)
    yield db_obj
    db_obj.close()


@pytest.fixture(scope="module")
def db_181(request):
    """
    db_host: 192.168.10.181
    """
    module_name = os.path.dirname(request.node.nodeid)[9:]
    enum_module_name = {
        "hy_jtgl": Config().hy_jtgl_default_database_181,
        "hy_lysh": Config().hy_lysh_default_database_181,
        "hy_hydd": Config().hy_hydd_default_database_181,
        "hy_lytc": Config().hy_lytc_default_database_181,
        "hy_xxfb": Config().hy_xxfb_default_database_181,
        "hy_lyjc": Config().hy_lyjc_default_database_181
    }
    default_db = enum_module_name.get(module_name)
    db_obj = pymysql.connect(host=Config().connect_url_db_181,
                             port=3306,
                             user=Config().username_db_181,
                             password=Config().password_db_181,
                             database=default_db)
    yield db_obj
    db_obj.close()


@pytest.fixture(scope='module')
def db_184():
    """
    db_host: 192.168.10.184
    """
    db_obj = pymysql.connect(host=Config().connect_url_db_184,
                             port=3306,
                             user=Config().username_db_184,
                             password=Config().password_db_184,
                             database=Config().default_db_184)
    yield db_obj
    db_obj.close()


@pytest.fixture(scope="module")
def db_201():
    """
    db_host: 192.168.10.201
    """
    db_obj = pymysql.connect(host=Config().connect_url_db_201,
                             port=3306,
                             user=Config().username_db_201,
                             password=Config().password_db_201,
                             database=Config().default_db_201)
    yield db_obj
    db_obj.close()


@pytest.fixture(scope="session")
def jira_obj():
    """
    jira_host : 192.168.10.216:8200
    """
    _jr_url = Config().jira_url  # jira地址
    _jr_username = Config().jira_username  # jira用户名
    _jr_password = Config().jira_password  # 密码
    jr_server = jira.JIRA(server=_jr_url,
                          basic_auth=(_jr_username, _jr_password))
    yield jr_server


@pytest.fixture(scope="module")
def driver_obj():
    with webdriver.Chrome() as driver:
        yield driver


if __name__ == '__main__':
    pass
